import jieba
from service.map import Map
from service.weather import WeatherInfo
from service.fetch_stock_data import fetch_stock_data, find_stock_code
from service.fetch_stock_name import extract_stock_names
from flask import Blueprint, request
from utils.Response import Response
from service.chatbot import ChatBot

chat_bp = Blueprint('ask_bp', import_name=__name__, url_prefix='/chat')


# 中文分词
def chinese_segmentation(text):
    return jieba.lcut(text)


# 定义关键信息和对应的操作
key_info_actions = {
    "天气": "调用天气API",
    "经纬度": "调用经纬度API",
    "股票": "调用股票API",

}

day_map = {
    "今天天气": 0,
    "今天":0,
    "明天": 1,
    "后天": 2,
    "未来": 300,
}


@chat_bp.get("")
def ask():
    day = 0
    answer = ""
    ID=""
    # 用户输入问题
    user_input = request.args.get('msg', '')
    print(user_input)
    with open("data/latast_userID.txt", 'r', encoding='utf-8') as file:
        ID = file.read()  # 读取整个文件内容为一个长字符串

    wxAPI = True
    # 中文分词
    tokens = chinese_segmentation(user_input)
    print(tokens)
    # 提取关键信息
    key_info = []
    city = ""

    for token in tokens:
        for key in key_info_actions:
            if key in token:
                action = key_info_actions[key]
                key_info.append(key)
                if "天气" in token:
                    # 如果当前token包含"天气"，那么我们就检查整个tokens列表是否包含"今天"、"明天"、"后天"或"未来几天"
                    day_name = next((day for day in tokens if day in ["今天","今天天气", "明天", "后天", "未来"]), None)
                    # 如果tokens列表中包含"今天"、"明天"、"后天"或"未来几天"，那么执行你的elif语句
                    day = day_map[day_name]
                break
        else:
            if any(substring in token for substring in ["省", "市", "区", "县"]):
                city += token

    # print(city)
    # 如果存在关键信息，则执行相应操作
    if key_info:
        wxAPI = False
        for key in key_info:
            action = key_info_actions[key]
            if action == "调用天气API":
                # 在这里执行调用天气API的操作
                data = Map.tengxun(city)
                temp = "3d"
                weather_info = WeatherInfo()
                if day == 300:
                    result ='\n'.join(weather_info.get_weather_info(data, temp))
                else:
                    result = weather_info.get_weather_info(data, temp)[day]
                print(result)
                answer = result
            elif action == "调用经纬度API":
                # 在这里执行获取最新新闻的操作
                try:
                    data = Map.tengxun(city)
                    a, b = map(float, data.split(','))
                    answer = city + "的经度为" + str(a) + ",纬度为" + str(b)
                except:
                    answer="请求失败"
            elif action == "调用股票API":

                answer = "调用股票API"
                # # 在这里执行查询股票信息的操作
                # # print(user_input)
                # stock_name = extract_stock_names(user_input)
                # stock_name = stock_name[0]
                # print(stock_name)
                # stock_code = find_stock_code(stock_name)
                # print(stock_code)
                # information = fetch_stock_data(stock_code)
                # print(information)

                answer ="调用股票API"
                # 在这里执行查询股票信息的操作
                # print(user_input)
                stock_name = extract_stock_names(user_input)
                stock_name = stock_name[0]
                print(stock_name)
                stock_code = find_stock_code(stock_name)
                print(stock_code)
                information = fetch_stock_data(stock_code)
                answer = information
                print(information)

                # # print("调用股票API")

    if wxAPI:
        chatbot = ChatBot(ID)
        answer = chatbot.chat(user_input)
        print(answer)
        wxAPI = True
    return Response.success(data=answer)
